package com.example.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {
	private ImageView imageview;
	PicHandler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		handler = new PicHandler();
		imageview = (ImageView) findViewById(R.id.imageview);
		
		new Thread(){
			public void run() {
				Drawable drawable = getPic();
			};
		}.start();
		
		
	}

	
	private Drawable getPic() {
		String urlStr = "http://img.pconline.com.cn/images/upload/upc/tx/auto5/1305/19/c2/21104612_1368968164396_500.jpg";
		Drawable drawable = null;
		try {
			URL url = new URL(urlStr);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			if(con.getResponseCode() == 200){
				InputStream is = con.getInputStream();
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				BitmapDrawable bd = new BitmapDrawable(bitmap);  
		        drawable = (Drawable) bd;  
		        Message msg = new Message();
		        msg.obj = drawable;
		        handler.sendMessage(msg);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return drawable;
	}
	
	class PicHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			imageview.setImageDrawable((Drawable) msg.obj);
		}
	}

}
